<template>
  <div class="app-main-container">
    <div class="df" style="height: 100%">
      <div class="sell_left">
        <div class="df">
          <el-select
            v-model="selectProNmae"
            class="flex1"
            :placeholder="$t('message.qbxm')"
            clearable
            @change="conditionChange()"
          >
            <el-option
              v-for="item in project.projectList"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
            />
          </el-select>
          <el-date-picker
            v-model="param.date"
            type="date"
            class="ml20 flex1"
            :placeholder="$t('message.xzrq')"
            value-format="yyyy-MM-dd"
            :clearable="false"
            :editable="false"
            @change="conditionChange()"
          />
        </div>
        <div class="mt10 sell_wrap">
          <div
            v-for="(item, index) in saleTickets"
            :key="index"
            class="card-style"
            :class="item.isSelect ? 'select-style' : 'normal-style'"
            @click="selectTick(index)"
          >
            <div class="img-div">
              <el-image
                v-if="item.ticketPic"
                :preview-src-list="[item.ticketPic]"
                fit="contain"
                :src="item.ticketPic"
                alt=""
              />
              <img v-else src="@/assets/images/default_space.png" />
            </div>
            <div class="combo_card_right">
              <div class="card-name">{{ item.name }}</div>
              <div class="time-style">
                <span class="placeholder6">{{ $t("message.syxm") }}：</span
                ><span class="flex1">{{ item.projectName }}</span>
              </div>
              <div class="time-style">
                <span class="placeholder6">{{ $t("message.yxsj") }}：</span
                >{{ item.projectTime }}
              </div>
              <div class="specific">
                <div class="card-first-price secondColor">
                  {{ $t("message.rmbfh") }}{{ item.price }}
                </div>
                <div class="num-module-style">
                  <div class="sale-style">
                    <span class="num-title-style"
                      >{{ $t("message.yishou") }}：</span
                    >
                    <span>{{ item.saleNum }}</span>
                  </div>
                  <span class="ml10 mr10 placeholder6"> | </span>
                  <div class="surplus-style">
                    <span class="num-title-style"
                      >{{ $t("message.sy") }}：</span
                    >
                    <span>{{ item.surplusDay }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div>
          <Paginations
            :integrated="false"
            :page="salePagination.page"
            :total="saleTotal"
            :page-size="salePagination.rows"
            @current-change="salePageChange"
          />
        </div>
      </div>
      <div class="separator" />
      <div class="flex1">
        <div class="member_wrap">
          <div class="df">
            <MemberSearch
              ref="MemberSearchRef"
              class="flex1"
              @clear="memberClear"
              @select="memberSelect"
            />
            <el-button class="ml10" type="primary" @click="memberClear">{{
              $t("message.sk")
            }}</el-button>
          </div>
          <div class="df mt20 mb20">
            <span class="flex1"
              >{{ $t("message.name") }}：{{ memberInfo.nickName || "-" }}</span
            >
            <span class="flex1"
              >{{ $t("message.sjh") }}：{{ memberInfo.phone || "-" }}</span
            >
            <span class="flex1"
              >{{ $t("message.hydj") }}：{{ memberInfo.cardName || "-" }}</span
            >
            <span class="flex1"
              >{{ $t("message.czje") }}：{{
                memberInfo.rechargeMoney || "0.00"
              }}</span
            >
            <span class="flex1"
              >{{ $t("message.zsye") }}：{{
                memberInfo.giveMoney || "0.00"
              }}</span
            >
          </div>
        </div>
        <div class="tables">
          <el-table
            :data="selectedMessage"
            border
            fit
            :header-row-class-name="'table-header'"
            class="doumee-element-table"
          >
            <el-table-column
              align="center"
              :label="$t('message.mp')"
              prop="name"
              min-width="120"
              show-overflow-tooltip
            />
            <el-table-column
              align="center"
              :label="$t('message.dprice')"
              prop="price"
              min-width="70"
              show-overflow-tooltip
            />
            <el-table-column
              align="center"
              :label="$t('message.yj')"
              prop="deposit"
              min-width="40"
              show-overflow-tooltip
            />
            <!-- <el-table-column align="center" :label="$t('message.sysj2')" prop="fitDate" min-width="160" show-overflow-tooltip /> -->
            <el-table-column
              align="center"
              :label="$t('message.num')"
              width="120"
            >
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.count"
                  @change="selectTickNum(scope.row.count)"
                  size="small"
                  :step="1"
                  step-strictly
                  :min="1"
                  :max="Number(scope.row.surplusDay)"
                  :label="$t('message.num')"
                  style="width: 100%"
                />
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              :label="$t('message.xiaoji')"
              min-width="40"
              show-overflow-tooltip
            >
              <template v-slot="scope">
                <span>{{
                  (scope.row.price * scope.row.count).toFixed(2)
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              :label="$t('message.caozuo')"
              min-width="50"
            >
              <template slot-scope="scope">
                <el-button
                  v-preventReClick
                  type="text"
                  class="delete-style"
                  @click="toDelete(scope.$index)"
                  >{{ $t("message.del") }}</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="selectedMessage.length" class="bottom-style">
          <div class="price_wrap">
            <div class="sum-style">
              <span class="sum-title">{{ $t("message.heji") }} ：</span>
              <span class="sum-value secondColor">{{ totalMoney }}</span>
            </div>
            <!-- <div class="sum-style">
              <span class="sum-title">{{ $t('message.zhje') }} ：</span>
              <span class="sum-value secondColor">{{ totalMoney }}</span>
            </div>
            <div class="sum-style">
              <span class="sum-title">{{ $t('message.yhje') }}：</span>
              <span class="sum-value secondColor">{{ totalMoney }}</span>
            </div> -->
          </div>
          <div class="sub_order">
            <el-input
              v-model="remark"
              :placeholder="$t('message.qsr') + $t('message.ddbz')"
            />
            <el-button
              v-preventReClick
              :loading="subLoading"
              class="ml20"
              type="primary"
              @click="totalAction"
              >{{ $t("message.ddjs") }}
            </el-button>
            <el-button @click="clearOrder">{{ $t("message.clear") }}</el-button>
          </div>
        </div>
      </div>
    </div>
    <orderDialog
      ref="child"
      @openSuccess="subLoading = false"
      @orderSuccess="orderSuccess"
    />
  </div>
</template>

<script>
import { getProjectList, onSaleTicket, printOrder } from "@/api";
import { parseTime } from "@/utils";
import orderDialog from "@/components/order";
import MemberSearch from "@/components/MemberSearch";
export default {
  name: "TicketSell",
  components: {
    orderDialog,
    MemberSearch,
  },
  data() {
    return {
      subLoading: false,
      memberInfo: {},
      meta: [],
      selectProNmae: "",
      date: "",
      saleTickets: [],
      salePagination: {
        rows: 20,
        page: 1,
      },
      saleTotal: 0,
      selectedMessage: [],
      project: {
        projectList: [],
      },
      param: {
        date: parseTime(new Date()),
      },
      remark: "",
    };
  },
  computed: {
    swiper() {
      return this.$refs.mySwiper.$swiper;
    },
    totalMoney() {
      let money = 0.0;
      this.selectedMessage.forEach((ticket) => {
        money =
          (Number(ticket.price) + Number(ticket.deposit)) *
            Number(ticket.count) +
          money;
      });
      return parseFloat(money).toFixed(2);
    },
  },
  created() {
    this.meta = this.$route.meta.buttons || [];
    this.getProList();
    this.getTickets();
  },
  methods: {
    getList() {
      this.$router.push({ name: "TicketOrder" });
    },
    memberSelect(item) {
      this.memberInfo = item;
      this.androidSelectMember();
    },
    memberClear() {
      this.$refs.MemberSearchRef.clearSearch();
      this.memberInfo = {};
      this.androidSelectMember();
    },
    orderSuccess() {
      this.memberClear();
      this.saleTickets = [];
      this.getTickets();
      this.selectedMessage = [];
    },
    printTC(id) {
      if (window.Android) {
        Android.print("TICKETTPML", id, "");
        return;
      }
      printOrder({
        param: {
          contentMap: {},
          venueId: sessionStorage.getItem("venueId"),
          workId: id,
          templateCode: "TICKETTPML",
        },
      }).then((res) => {
        // console.log(res)
      });
    },
    getProList() {
      getProjectList({
        pagination: {
          page: 1,
          rows: 1000,
          firstQueryTime: parseTime(new Date()),
        },
        param: {
          venueId: sessionStorage.getItem("venueId"),
          projectName: "",
          type: "1",
          status: "",
        },
      }).then((res) => {
        if (res.errorCode !== "000000") return;
        this.project.projectList = res.recordList;
      });
    },
    conditionChange() {
      this.getTickets();
    },
    getTickets() {
      onSaleTicket({
        param: {
          projectId: this.selectProNmae,
          saleDate:
            this.param.date === null ? parseTime(new Date()) : this.param.date,
          venueId: sessionStorage.getItem("venueId"),
        },
        pagination: this.salePagination,
      })
        .then((res) => {
          if (res.errorCode !== "000000") return;
          this.saleTickets = res.recordList;
          this.saleTotal = res.totalCount;
          this.saleTickets.forEach((item) => {
            item.isSelect = false;
            this.selectedMessage.forEach((select) => {
              if (select.id === item.id) {
                item.isSelect = true;
              }
            });
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    clearOrder() {
      console.log("clearOrder");
      if (window.Android) {
        let datas = [];
        let info = { datas };
        let obj = JSON.stringify(info);
        Android.setGoods(obj);
      }
      this.selectedMessage = [];
      this.saleTickets.forEach((item) => {
        item.isSelect = false;
      });
    },
    salePageChange(val) {
      this.salePagination.page = val;
      this.getTickets();
    },
    // 安卓选择会员
    androidSelectMember() {
      console.log(this.memberInfo, "===============4");
      let info = {
        showAvatar:
          this.memberInfo.showFaceUrl || this.memberInfo.showAvatar || "", //头像
        nickName: this.memberInfo.nickName || "", // //昵称
        phone: this.memberInfo.phone || "",
        integral: this.memberInfo.integral || "", // //积分
        totalMoney:
          (this.memberInfo.rechargeMoney + this.memberInfo.giveMoney).toFixed(
            2
          ) || 0, //总金额
      };
      console.log(info, "===============1");
      let obj = JSON.stringify(info);
      if (window.Android) {
        Android.setMember(obj);
        return;
      }
    },
    formatNumber(value) {
      // 显示为两位小数但保留原始数值类型
      return value ? value.toFixed(2) : "0.00";
    },
    parseNumber(value) {
      // 输入时自动过滤非数字字符并保留两位小数
      return parseFloat(String(value).replace(/[^\d.]/g, "") || 0);
    },
    // 商品数量增加 减少
    selectTickNum(val) {
      val = parseFloat(val).toFixed(2);
      console.log(val, "===============12");
      this.androidHandle();
    },
    androidHandle() {
      let datas = [];
      console.log(this.selectedMessage, "4============");
      this.selectedMessage.forEach((item) => {
        datas.push({
          title: item.name,
          price: item.price,
          deposit: item.deposit || 0,
          num: item.count,
          infos: [
            `${this.$t("message.dprice")}:${this.$t("message.rmbfh")}${
              item.price
            }`,
            `${this.$t("message.yj")}:${this.$t("message.rmbfh")}${
              item.deposit || 0
            }`,
          ],
        });
      });
      let info = {
        datas,
      };
      console.log(info, "===============3s");
      let obj = JSON.stringify(info);
      if (window.Android) {
        Android.setGoods(obj);
        return;
      }
    },
    selectTick(index) {
      const item = this.saleTickets[index];
      if (item.surplusDay < 1) {
        return this.$message.warning(this.$t("message.gkcbz"));
      }
      if (item.isSelect) {
        const index = this.selectedMessage.findIndex((i) => i.id === item.id);
        this.selectedMessage.splice(index, 1);
      } else {
        this.selectedMessage.push({
          id: item.id,
          name: item.name,
          price: item.price,
          deposit: item.deposit || 0,
          count: 1,
          fitDate: item.saleDate + " " + item.projectTime,
          surplusDay: item.surplusDay,
        });
        console.log(this.selectedMessage, "===============1");
      }
      this.saleTickets[index].isSelect = !this.saleTickets[index].isSelect;
      this.androidHandle();
    },
    toDelete(index) {
      this.saleTickets.forEach((item) => {
        if (item.id === this.selectedMessage[index].id) {
          item.isSelect = false;
        }
      });
      this.selectedMessage.splice(index, 1);
      this.androidHandle();
    },
    totalAction() {
      const p = [];
      const { remark, memberInfo } = this;
      this.selectedMessage.forEach((select) => {
        p.push({
          id: select.id,
          num: select.count,
        });
      });
      const config = { ...config, p, remark, memberId: memberInfo.id };
      this.subLoading = true;
      setTimeout(() => {
        this.subLoading = false;
      }, 3000);
      try {
        this.$refs.child.continuePay(config, "ticket");
      } catch (error) {
        this.subLoading = true;
      }
    },
  },
  beforeRouteLeave(to, from, next) {
    console.log(to, from, "to, from离开页面销毁订单");
    if (window.Android) {
      this.clearOrder();
      this.memberClear();
      Android.clearOrder();
    }
    next(); // 始终允许导航
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.app-main-container {
  height: calc(100% - 40px);
}
.sell_left {
  height: 100%;
  width: 520px;
  .sell_wrap {
    height: calc(100% - 100px);
    overflow: auto;
  }
}
.tables {
  height: calc(100% - 200px);
  overflow: auto;
}
.separator {
  margin: 0 20px;
  width: 1px;
  height: 100%;
  background-color: #dfe2e8;
}
.data-picker-style {
  margin-left: 20px;
}
.delete-style {
  color: $SecondColor;
}

.card-style {
  cursor: pointer;
  width: 100%;
  // height: 104px;
  margin-bottom: 10px;
  display: flex;
  padding: 10px;
  box-sizing: border-box;
  .img-div {
    width: 60px;
    height: 60px;
    margin-right: 10px;
    display: flex;
    img {
      width: 100%;
      border-radius: 2px;
    }
  }
  .combo_card_right {
    flex: 1;
    .card-name {
      margin-bottom: 10px;
      line-height: 14px;
    }
    .card_type {
      margin-bottom: 10px;
      font-size: 12px;
      line-height: 12px;
    }
    .time-style {
      margin-bottom: 12px;
      font-size: 12px;
      line-height: 12px;
      // display: flex;
      .placeholder6 {
        // width: 62px;
      }
    }
    .specific {
      display: flex;
      line-height: 14px;
      justify-content: space-between;
      .card-first-price {
        font-size: 14px;
      }
      .num-module-style {
        font-size: 12px;
        .sale-style {
          float: left;
        }
        .surplus-style {
          float: right;
        }
        .num-title-style {
          color: #666666;
        }
      }
    }
  }
}
.select-style {
  border: solid 1px $primaryColor;
}
.normal-style {
  border: solid 1px #d8d8d8;
}

.bottom-style {
  background: #f7f7f7;
  border-radius: 2px;
  padding: 20px;
  .price_wrap {
    display: flex;
    margin-bottom: 20px;
    .sum-style {
      font-size: 16px;
      margin-right: 75px;
      .sum-title {
        color: #222;
      }
      .sum-value {
        font-size: 17px;
        font-weight: 700;
      }
    }
  }
  .sub_order {
    display: flex;
  }
}
.count-style {
  margin-left: 5px;
  margin-right: 5px;
}
.pay-style {
  min-width: 80px;
  padding-left: 5px;
  padding-right: 5px;
  height: 30px;
  font-size: 15px;
  line-height: 1px;
  vertical-align: middle;
}
.slelect-pay-style {
  background-color: $primaryColor;
  color: #fff;
}
.normal-pay-style {
  border: 1px solid #d8d8d8;
  background-color: #fff;
  color: #222;
}
.messgae-style {
  color: $SecondColor;
}
.price-style {
  font-size: 17px;
  font-weight: 500;
}
.unit-style {
  margin-right: 20px;
}
.bottom-speace-style {
  margin-bottom: 10px;
}
.card-message {
  margin-bottom: 10px;
  background-color: #f2f2f2;
  height: 60px;
  line-height: 20px;
  .first-line {
    height: 30px;
    padding: 5px;
    .message-title-style {
      color: #999;
    }
    .card-name-style {
      display: inline-block;
      border: 1px #999 solid;
      border-radius: 4px;
      background-color: #fff;
      font-size: 12px;
      padding-left: 5px;
      padding-right: 5px;
      height: 20px;
      text-align: center;
    }
    .close-style {
      font-size: 20px;
      float: right;
      margin-right: 5px;
      margin-top: -2px;
      padding: 0;
      border: 0px #999 solid;
    }
    .message-value-style {
      margin-right: 15px;
      color: #222;
    }
  }
}
.footer-style {
  display: flex;
  justify-content: space-between;
  background-color: #f2f2f2;
  margin: -10px -20px -30px;
  height: 50px;
  .bottom-left {
    margin-left: 20px;
    height: 20px;
    margin-top: 15px;
    .sum-title-style {
      font-size: 15px;
      color: #222;
    }
    .sum-pay-value-style {
      font-size: 17px;
      font-weight: 500;
      color: $SecondColor;
    }
    .dis-title-style {
      font-size: 14px;
      color: #222;
    }
    .discoun-style {
      font-size: 16px;
      color: $SecondColor;
    }
  }
  .bottom-right {
    margin-right: 20px;
    margin-top: 10px;
    height: 30px;
    .pay-action-style {
      width: 100px;
      height: 30px;
      font-size: 15px;
      line-height: 1px;
      vertical-align: middle;
    }
  }
}
</style>
